<?php
namespace app\service;
use think\facade\Db;
use app\model\CategoryModel;
use Exception;

class CategoryService{  
    public function all($params){
        $where=[];     
        if(!empty($params['pid'])){
            $where[] = ['pid','=',$params['pid']];   
        }        
        $users = CategoryModel::where($where)->select();        
        return $users;
    }

    public function list($params){        
        $page = $params['page'];
        $pageCount = $params['page_count'];        
        $data = CategoryModel::where('pid',$params['pid'])->page($page,$pageCount)->order('id','desc')->select(); 
        $count = CategoryModel::where('pid',$params['pid'])->count(); 
        return ["list"=>$data,"count"=>$count];
    } 
    
    public function info($id){
        $categorys = CategoryModel::where('pid',$id)->select(); 
        return $categorys;
    }

    public function byPid($pid){
        $categorys = CategoryModel::where('pid',$pid)->select(); 
        return $categorys;
    } 

    public function save($params){              
        if(empty($params['id'])){
            $data = CategoryModel::where('title',$params['title'])->find();
            if($data){
                throw new Exception("名称已存在");
            }
            $data = CategoryModel::create($params); 
        }else{
            $data = CategoryModel::update($params, ['id' => $params['id']]); 
        }        
        return $data;
    }

    public function delete($params){   
        $data = CategoryModel::destroy($params['id']);         
        return $data;
    }
}